package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * t添加分类
     */
    @PostMapping
    public R<String> save(@RequestBody Category category, HttpSession session) {
        //1获取当前登入者
        Long empId = (long) session.getAttribute("employee");
        //2.补全category信息
        category.setCreateUser(empId);
        category.setUpdateUser(empId);
        categoryService.save(category);
        return R.success("添加类别成功");
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public R<Page<Category>> save(Integer page, Integer pageSize) {
        Page<Category> pageResult = categoryService.findByPage(page, pageSize);
        return R.success(pageResult);
    }

    /**
     * 根据id删除类别
     */
    @DeleteMapping
    public R<String> delete(long id) {
        categoryService.removeById(id);
        return R.success("类别删除成功");
    }

    /**
     * 根据id修改类别数据
     */
    @PutMapping
    public R<String> update(@RequestBody Category category, HttpSession session) {
        //获取登陆者数据
        long empId = (Long) session.getAttribute("employee");
        //修改修改者信息
        category.setUpdateUser(empId);
        categoryService.updateById(category);
        return R.success("修改成功");
    }
    /**
     * 作用：根据Type查询类别集合
     * @param type  类别的type
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Integer type){
        List<Category> categoryList= categoryService.list(type);
        return R.success(categoryList);
    }

}
